package org.groupg.filetodb.model.factory;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import org.apache.commons.dbcp2.BasicDataSource;
import org.groupg.filetodb.model.Task;
import org.groupg.filetodb.model.finals.JDBC;

import javax.sql.DataSource;
import java.io.File;
import java.util.Properties;

/**
 * 任务的构造类，将构造过程简化并添加相应的教研
 */
public class TaskFactory {

    public static Task instantiateTask(String taskID, String taskName, String taskDescription, File taskFileDir, String jdbcDriver, String jdbcUrl, String jdbcUser, String jdbcPwd) {
        Properties properties = new Properties();
        properties.put(JDBC.driver, jdbcDriver);
        properties.put(JDBC.url, jdbcUrl);
        properties.put(JDBC.username, jdbcUser);
        properties.put(JDBC.password, jdbcPwd);
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(jdbcDriver);
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUser);
        dataSource.setPassword(jdbcPwd);
        dataSource.setInitialSize(100);
        dataSource.setDefaultAutoCommit(Boolean.TRUE);
        dataSource.setAutoCommitOnReturn(Boolean.TRUE);
        return instantiateTask(taskID,taskName,taskDescription,taskFileDir,properties,dataSource);
    }


    public static Task instantiateTask(String taskID, String taskName, String taskDescription, File taskFileDir, Properties dbProperties, DataSource dataSource) {
        Task task = new Task();
        task.setTaskID(taskID);
        task.setTaskName(taskName);
        task.setTaskDescription(taskDescription);
        task.setTaskFileDir(taskFileDir);
        task.setDbProperties(dbProperties);
        task.setDataSource(dataSource);
        checkMustNotNull(task);
        return task;
    }

    private static void checkMustNotNull(Task task) {
        Assert.notNull(task, "任务对象不能为空！");
        Assert.notNull(task.getTaskID(), "任务编号不能为空！");
        Assert.notNull(task.getTaskName(), "任务名称不能为空！");
        Assert.notNull(task.getTaskFileDir(), "任务文件目录不能为空！");
        if (!task.getTaskFileDir().exists()) {
            FileUtil.mkdir(task.getTaskFileDir());
        }
        if (task.getDbProperties() == null || task.getDbProperties().isEmpty() || task.getDataSource() == null) {
            throw new NullPointerException("数据库链接不能为空");
        }
    }
}
